#!/usr/bin/python
# coding:utf-8
import logging
from logging.handlers import RotatingFileHandler

from flask import Flask
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
import redis
from flask_wtf import CSRFProtect

db = SQLAlchemy()
rs = None  # type: redis.StrictRedis


def setup_log(config_mode):
    """配置日志"""

    logging.basicConfig(level=config_mode.LOG_LEVEL)  # 指定日志级别
    # 指定日志的存放地址, 大小, 和备用数量
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 指定日志的输出格式
    formatter = logging.Formatter("%(levelname)s %(filename)s %(lineno)d %(message)s")
    file_log_handler.setFormatter(formatter)  # 将格式配置到handler上
    logging.getLogger().addHandler(file_log_handler)  # 将handler配置到日志上


def create_app(config_mode):
    """创建app, db, rs"""

    setup_log(config_mode)  # 调用函数配置日志

    app = Flask(__name__)
    app.config.from_object(config_mode)  # 创建app,并导入对象配置

    global db, rs  # 对db, rs进行设置
    db.init_app(app)
    # decode_responses 为在取值时自动解码
    rs = redis.StrictRedis(host=config_mode.REDIS_HOST, port=config_mode.REDIS_PORT, decode_responses=True)

    Session(app)  # 设置session
    CSRFProtect(app)  # 开启CSRF保护

    from game.modules.lobby import lobby_blue
    app.register_blueprint(lobby_blue)

    from game.modules.table import table_blue
    app.register_blueprint(table_blue)

    from game.modules.learn import learn_blue
    app.register_blueprint(learn_blue)

    return app
